package com.ycb.bookserver.chat;

import com.alibaba.fastjson.JSON;
import com.book.exception.ChatSendErrorException;
import com.ycb.book.entity.User;
import com.ycb.bookserver.chat.utils.ApplicationContextProvider;
import com.ycb.bookserver.chat.utils.MessageUtils;
import com.ycb.bookserver.chat.utils.pojo.Message;
import com.ycb.bookserver.mapper.UserMapper;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Slf4j
@Component
@ServerEndpoint(value = "/chat/{id}")//此处id是指当前用户的id
//configurator = GetHttpSessionConfiguration.class
public class chatEndpoint {
    //存放每个客户端对应的chatendpoint
    private static CopyOnWriteArraySet<chatEndpoint> chatEndpoints = new CopyOnWriteArraySet<>();
    //与与某一个客户端之间的会话
    private Session session;
    private Long userId;

    private UserMapper userMapper= ApplicationContextProvider.getBean(UserMapper.class);

    //当客户端与服务端连接上后自动进行
    @OnOpen
    public void onOpen(Session session, @PathParam("id") Long Id) {
        //User user = userMapper.getUserById(Id);
        this.session = session;
        this.userId = Id;
        //加上当前客户端
        chatEndpoints.add(this);
        log.info("当前客户端已链接");
    }


    //断开连接后进行
    @OnClose
    public void onClose(Session session) {
        //用户下线后，把他剔除
        chatEndpoints.remove(this);
        log.info("当前客户端已失去链接");
    }
    @OnError
    public void onError(Session session, Throwable throwable) {
        log.info("发生错误");
        throwable.printStackTrace();
    }


    //消息发送到服务端后被调用
    @OnMessage
    public void onMessage(String message) {//此处message是指客户端给服务器的JSON
        //把消息推送给指定用户
        Message msg = JSON.parseObject(message, Message.class);

        Long fromId = msg.getFromId();
        Long toId = msg.getToId();
        String mess = msg.getMessage();
        String message1 = MessageUtils.getMessage(false,fromId, toId, mess);
        //获取接收方相关
        for (chatEndpoint ce : chatEndpoints) {
            if (ce.userId.equals(toId)) {
                try {
                    ce.session.getBasicRemote().sendText(message1);
                    log.info("消息推送成功");

                } catch (IOException e) {
                    log.info("消息推送失败");
                    throw new ChatSendErrorException("消息推送失败error");
                }
            }
        }


    }
}
